package com.wx.io.netty.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * netty Server 端
 * @author wangxun
 * @version 1.0
 * @description: netty Server 小练习
 * @date 2021/1/5 4:06 下午
 */
public class NettyServer {
    static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
    public static void main(String[] args) {
        logger.info("ssssss");
        // 线程池
        NioEventLoopGroup boss = new NioEventLoopGroup();
        // 处理传输线程池 业务线程池
        NioEventLoopGroup worker = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // boss : 是设置要处理ServerSocketChannel的selector线程池
        // worker: 是设置要处理SocketChannel的selector线程池
        serverBootstrap.group(boss, worker);
        serverBootstrap.channel(NioServerSocketChannel.class);
        // 设置通讯的selector的处理器 这用了一个模板共享@Sharable的handler作为跳转模板
        serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {

            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                // 获取通道的管道,依次执行handler
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                pipeline.addLast(new HttpRequestDecoder());
                pipeline.addLast(new MyInBound());
            }
        });

        try {
            serverBootstrap.bind(9999).sync()// 阻塞当前线程到服务启动起来
                    .channel().closeFuture().sync(); // 阻塞当前线程到服务停止
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
